import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-03
 * Time：13:20
 */

//1.类的属性名字要和json的key保持一致 2.属性时public或者提供getter方法
class Student {
    public int classId;
    public int studentId;
}

@WebServlet("/studentInfo")
public class studentInfo extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //resp.setContentType("text/html; charset=utf8");
        //x-www-form-urlencoded
//        String classId = req.getParameter("classId");
//        String stuId = req.getParameter("studentId");
//        resp.getWriter().write("className" + "：" + classId + "<br/>" + "StuName" + stuId);

        //JSON格式
        ObjectMapper objectMapper = new ObjectMapper();
        //从请求的body中读取，并解析
        //使用readValue来把json字符串转成java对象
        Student student = objectMapper.readValue(req.getInputStream(), Student.class);
        System.out.println(student.classId + ", " + student.studentId);
        resp.getWriter().write(student.classId + ", " + student.studentId);
    }
}
